//
//  DynamicServer.m
//  WeCommunity
//
//  Created by mac on 2017/6/21.
//  Copyright © 2017年 lzy. All rights reserved.
//

#import "DynamicServer.h"
#import "PhotoAlbumModel.h"

//leanCloud表名
#define DYNAMIC_CLASS_NAME @"Dynamic"




#define MIN_READTOTAL_NUM 1500

#define MIN_REPORT_NUM 1

static DynamicServer * dynamicServer = nil;

@interface DynamicServer ()



@end


@implementation DynamicServer

+(DynamicServer *)shared
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dynamicServer = [[DynamicServer alloc] init];
        
    });
    return dynamicServer;
}

#pragma mark - 设置用户权限
-(void)setUserPermissionsWithObject:(AVObject *)object
                               publicRead:(BOOL)read
                              publicWrite:(BOOL)write
                          writeList:(NSArray *)writeList
{
    AVACL *acl = [AVACL ACL];
    [acl setPublicReadAccess:read];// 设置公开的「读」权限，任何人都可阅读
    [acl setPublicWriteAccess:write];
    if (writeList.count > 0) {
       [acl setWriteAccess:YES forUser:[AVUser currentUser]];// 为当前用户赋予「写」权限，有且仅有当前用户可以修改这条 Post
    }
    object.ACL = acl;// 将 ACL 实例赋予 Post对象
}

#pragma mark - 发布动态
-(void)postDynamicWithModel:(PostDynamicModel *)model
                   complete:(void(^)(BOOL success, NSString *error))complete
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        AVObject * dynamic = [AVObject objectWithClassName:DYNAMIC_CLASS_NAME];
        [dynamic setObject:model.content forKey:@"content"];
        [dynamic setObject:@(model.dataType) forKey:@"dataType"];
        //图片资源
        NSMutableArray * imageList = [NSMutableArray array];
        for (PhotoAlbumModel * albumModel in model.imagelist) {
            if (!albumModel.fullScreenImage) {
                UIImage *image = [UIImage imageWithCGImage:[[albumModel.asset defaultRepresentation] fullScreenImage]];
                albumModel.fullScreenImage = image;
            }
            NSData *data = UIImageJPEGRepresentation(albumModel.fullScreenImage, 0.5);
            AVFile *file = [AVFile fileWithData:data];
            [imageList addObject:file];
        }
        [dynamic setObject:imageList forKey:@"imageList"];
        
        //用户
        AVUser *currentUser = [AVUser currentUser];
        [dynamic setObject:currentUser forKey:@"contact"];
        [dynamic setObject:currentUser.objectId forKey:@"contactId"];
        
        [dynamic saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (succeeded) {
                    complete(YES,nil);
                }else{
                    complete(NO,error.userInfo[@"NSLocalizedDescription"]);
                }
            });
        }];
    });
}

#pragma mark - 获取动态列表
-(void)loadDynamicDataWithDataType:(NSInteger)type
                          loadDate:(NSDate *)loadDate
                         loadCount:(NSInteger)loadCount
                          complete:(void(^)(BOOL success, NSString * error, NSArray *dataArray))complete
{
    AVQuery *query = [AVQuery queryWithClassName:DYNAMIC_CLASS_NAME];
    
    //根据条件查询不同的数据
    if (!loadDate) {
        loadDate = [NSDate date];
    }
    
    [query whereKey:@"dataType" equalTo:@(type)];
    [query whereKey:@"createdAt" lessThan:loadDate];//查询日期之前创建的数据
    [query orderByDescending:@"createdAt"]; //按时间排序 降序
    query.limit = loadCount; // 最多返回 x 条结果
    // owner 为 Pointer，指向 _User 表
    [query includeKey:@"contact"];
    // image 为 File
    [query includeKey:@"imageList"];
    
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (error) {
            complete(NO,error.userInfo[@"NSLocalizedDescription"],nil);
        }else{
            
            NSMutableArray * dataList = [NSMutableArray array];
            for (NSDictionary * dic in objects) {
                DynamicModel * model = [DynamicModel setValueFormObject:dic];
                [dataList addObject:model];
            }
            //加入广告
            dataList = [[GooGleAdMobMgr shared] getAdMobModelDataWithArray:dataList];
            
            complete(YES,nil,dataList);
        }
    }];
}



#pragma mark - 点赞
-(void)likeOrUnLikeDataWithDynamic:(DynamicModel *)model
                          complete:(void(^)(BOOL success, NSString *error, DynamicModel *model))complete
{
    
    //查询最新的数据
    [self findDynamicDataWithObjectId:model.objectId complete:^(BOOL success, NSString *error, DynamicModel *resultModel) {
        if (success) {
            model.likeList = [resultModel.likeList mutableCopy];
            
            AVObject * dynamic =[AVObject objectWithClassName:DYNAMIC_CLASS_NAME objectId:model.objectId];
            if (!model.isLike) {
                [dynamic addObject:[UserInfoManger shared].contact.objectId forKey:@"likeList"];
            }else{
                [dynamic removeObject:[UserInfoManger shared].contact.objectId forKey:@"likeList"];
            }
            [dynamic saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
                if (succeeded) {
                    
                    if (!model.isLike) {
                        [model.likeList addObject:[UserInfoManger shared].contact.objectId];
                    }else{
                        [model.likeList removeObject:[UserInfoManger shared].contact.objectId];
                    }
                    complete(YES,nil,model);
                }else{
                    complete(NO,error.userInfo[@"NSLocalizedDescription"],nil);
                }
            }];
            
        }else{
            complete(NO,error,nil);
        }
    }];
}

#pragma mark - 查找我赞过的内容
-(void)loadMyselfLikeDynamicWithLoadDate:(NSDate *)loadDate
                               loadCount:(NSInteger)loadCount
                                complete:(void(^)(BOOL success, NSString *error, NSArray *dataArray))complete
{
    AVQuery *query = [AVQuery queryWithClassName:DYNAMIC_CLASS_NAME];
    
    if (!loadDate) {
        loadDate = [NSDate date];
    }
    [query whereKey:@"likeList" equalTo:[UserInfoManger shared].contact.objectId]; //查询我赞过的
    [query whereKey:@"createdAt" lessThan:loadDate];//查询日期之前创建的数据
    [query orderByDescending:@"createdAt"]; //按时间排序 降序
    
    query.limit = loadCount; // 最多返回 x 条结果
    // owner 为 Pointer，指向 _User 表
    [query includeKey:@"contact"];
    // image 为 File
    [query includeKey:@"imageList"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (error) {
            complete(NO,error.userInfo[@"NSLocalizedDescription"],nil);
        }else{
            NSMutableArray * dataList = [NSMutableArray array];
            
            for (NSDictionary * dic in objects) {
                DynamicModel * model = [DynamicModel setValueFormObject:dic];
                
                [dataList addObject:model];
            }
            complete(YES,nil,dataList);
        }
    }];
}

#pragma mark - 查找某人的动态
-(void)loadSomeOneDynamicDataWithContactId:(NSString *)contactId
                                 loadDate:(NSDate *)loadDate
                                loadCount:(NSInteger)loadCount
                                 complete:(void(^)(BOOL success, NSString *error, NSArray *dataArray))complete
{
    AVQuery *query = [AVQuery queryWithClassName:DYNAMIC_CLASS_NAME];
    
    if (!loadDate) {
        loadDate = [NSDate date];
    }
    [query whereKey:@"contactId" equalTo:contactId]; //查询某人的动态
    [query whereKey:@"createdAt" lessThan:loadDate];//查询日期之前创建的数据
    [query orderByDescending:@"createdAt"]; //按时间排序 降序
    
    query.limit = loadCount; // 最多返回 x 条结果
    // owner 为 Pointer，指向 _User 表
    [query includeKey:@"contact"];
    // image 为 File
    [query includeKey:@"imageList"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (error) {
            complete(NO,error.userInfo[@"NSLocalizedDescription"],nil);
        }else{
            NSMutableArray * dataList = [NSMutableArray array];
            
            for (NSDictionary * dic in objects) {
                DynamicModel * model = [DynamicModel setValueFormObject:dic];
                
                [dataList addObject:model];
            }
            if (![[UserInfoManger shared].contact.objectId isEqualToString:contactId]) {
                //加入广告
                dataList = [[GooGleAdMobMgr shared] getAdMobModelDataWithArray:dataList];
            }
            complete(YES,nil,dataList);
        }
    }];
}


#pragma mark - 查询某一动态数据
-(void)findDynamicDataWithObjectId:(NSString *)objectId
                       complete:(void(^)(BOOL success,NSString *error, DynamicModel * resultModel))complete
{
    AVQuery *query = [AVQuery queryWithClassName:DYNAMIC_CLASS_NAME];
    // owner 为 Pointer，指向 _User 表
    [query includeKey:@"contact"];
    // image 为 File
    [query includeKey:@"imageList"];
    [query getObjectInBackgroundWithId:objectId block:^(AVObject *object, NSError *error) {
        if (!error) {
            DynamicModel * model = [DynamicModel setValueFormObject:object];
    
            complete(YES,nil,model);
        }else{
            complete(NO,error.userInfo[@"NSLocalizedDescription"],nil);
        }
    }];
}

#pragma mark - 删除数据
-(void)deleteDynamicWithObjectId:(NSString *)objectId
                        complete:(void(^)(BOOL success,NSString *error))complete
{
    AVObject * dynamic =[AVObject objectWithClassName:DYNAMIC_CLASS_NAME objectId:objectId];
    [dynamic deleteInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
        complete(succeeded,error.userInfo[@"NSLocalizedDescription"]);
    }];
}

#pragma mark - 批量删除数据
-(void)deleteDynamicWithObjects:(NSArray *)objects
                        complete:(void(^)(BOOL success,NSString *error))complete
{
    NSMutableArray * objectIds = [NSMutableArray array];
    for (DynamicModel * model in objects) {
        AVObject * dynamic =[AVObject objectWithClassName:DYNAMIC_CLASS_NAME objectId:model.objectId];
        [objectIds addObject:dynamic];
    }
    [AVObject deleteAllInBackground:objectIds block:^(BOOL succeeded, NSError * _Nullable error) {
        complete(succeeded,error.userInfo[@"NSLocalizedDescription"]);
    }];
}

#pragma mark - 举报
-(void)reportDynamicToAdmin:(DynamicModel *)model
                   complete:(void(^)(BOOL success, NSString *error, DynamicModel *model))complete
{
    //查询最新的数据
    [self findDynamicDataWithObjectId:model.objectId complete:^(BOOL success, NSString *error, DynamicModel *resultModel) {
        if (success) {
            model.reportList = [resultModel.reportList mutableCopy];
            
            AVObject * dynamic =[AVObject objectWithClassName:DYNAMIC_CLASS_NAME objectId:model.objectId];
            if (!model.isReport) {
                [dynamic addObject:[UserInfoManger shared].contact.objectId forKey:@"reportList"];
                NSNumber * reportCount = [NSNumber numberWithInteger:model.reportList.count + 1];
                [dynamic setObject:reportCount forKey:@"reportCount"];
            }else{
                complete(YES,nil,model);
                return ;
            }
            
            [dynamic saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
                if (succeeded) {
                    
                    if (!model.isReport) {
                        [model.reportList addObject:[UserInfoManger shared].contact.objectId];
                    }
                    complete(YES,nil,model);
                    
                }else{
                    complete(NO,error.userInfo[@"NSLocalizedDescription"],nil);
                }
            }];
            
        }else{
            complete(NO,error,nil);
        }
    }];
}

#pragma mark - 管理员获取被举报的动态
-(void)adminLoadDynamicDataWithDate:(NSDate *)loadDate
                           loadCount:(NSInteger)loadCount
                            complete:(void(^)(BOOL success, NSString * error, NSArray *dataArray))complete
{
    AVQuery *query = [AVQuery queryWithClassName:DYNAMIC_CLASS_NAME];
    

    if (!loadDate) {
        loadDate = [NSDate date];
    }
    [query whereKey:@"createdAt" lessThan:loadDate];//查询日期之前创建的数据
    [query whereKey:@"reportCount" greaterThanOrEqualTo:@(MIN_REPORT_NUM)];
    [query orderByDescending:@"createdAt"]; //按时间排序 降序

    query.limit = loadCount; // 最多返回 x 条结果
    // owner 为 Pointer，指向 _User 表
    [query includeKey:@"contact"];
    // image 为 File
    [query includeKey:@"imageList"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (error) {
            complete(NO,error.userInfo[@"NSLocalizedDescription"],nil);
        }else{
            
            NSMutableArray * dataList = [NSMutableArray array];

            for (NSDictionary * dic in objects) {
                DynamicModel * model = [DynamicModel setValueFormObject:dic];
                [dataList addObject:model];
            }
            complete(YES,nil,dataList);
        }
    }];
}

#pragma mark - 删除被举报的数据
-(void)deleteBeenReportedDynamicWithObjectId:(NSString *)objectId
                                    complete:(void(^)(BOOL success,NSString *error))complete
{
    //查询最新的数据
    [self findDynamicDataWithObjectId:objectId complete:^(BOOL success, NSString *error, DynamicModel *resultModel) {
        if (success) {
            AVObject * dynamic =[AVObject objectWithClassName:DYNAMIC_CLASS_NAME objectId:objectId];
            
            for (NSString * objId in resultModel.reportList) {
                [dynamic removeObject:objId forKey:@"reportList"];
            }
            [dynamic setObject:[NSNumber numberWithInt:0] forKey:@"reportCount"];

            [dynamic saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
                if (succeeded) {
                    complete(YES,nil);
                }else{
                    complete(NO,error.userInfo[@"NSLocalizedDescription"]);
                }
            }];
            
        }else{
            complete(NO,error);
        }
    }];
}




@end
